import React, { Component } from 'react';
import PropTypes from 'prop-types';
import style from '@/page/setting/setting.scss';
import { Upload, Icon, Modal } from 'antd'
import MModal from '@/component/common/MModal';
import { upload_picture } from '@/constants/ApiTypes';
import { API_URL } from '@/config';

class UploadImage extends Component {
    static propTypes = {
        btnText: PropTypes.string,
        fileChange: PropTypes.func
    };
    static defaultPropTypes = {
        btnText: '上传图片'
    };
    state = {
        previewVisible: false,
        previewImage: '',
        fileList: []
    };

    handleCancel = () => this.setState({ previewVisible: false });
    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true
        });
    };
    handleChange = ({ fileList }) => {
        fileList.forEach((val, index) => {
            if (val.status == 'done' && val.response && !val.response.status) {
                fileList[index].status = 'error';
                MModal.success({ title: '上传失败', content: val.response.info, duration: 1.5 })
            }
        });
        this.fileChange(fileList);
        this.setState({ fileList });
    };
    //返回生成上传成功图片id数组
    fileChange = fileList => {
        if (this.props.fileChange) {
            let newFileList = [];
            fileList.forEach(val => {
                if (val.response && val.response.status) {
                    newFileList.push(val.response.info[0].id);
                }
            });
            this.props.fileChange(newFileList);
        }
    };

    render() {
        const { btnText } = this.props;
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div className="upload-image-btn">
                <Icon type="plus" />
                <div className="ant-upload-text">{btnText}</div>
            </div>
        );
        return (
            <div className="setting-upload">
                <Upload
                    action={`${API_URL}/${upload_picture}`}
                    listType="picture-card"
                    accept=".jpg, .png"
                    name="image"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                >
                    {fileList.length >= 1 ? null : uploadButton}
                </Upload>
                <MModal visible={previewVisible} onClose={this.handleCancel} showMask width={520} height={520} zIndex={101}>
                    <div className="image-preview-modal">
                        <img alt="图片预览" src={previewImage} />
                    </div>
                </MModal>
            </div>
        );
    }
}

export default UploadImage;